package com.lbtc.service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lbtc.common.Constant;
import com.lbtc.dao.ProductMapper;
import com.lbtc.domian.Product;
import com.lbtc.exception.LbtcMallException;
import com.lbtc.exception.LbtcMallExceptionEnum;
import com.lbtc.query.ProductListQuery;
import com.lbtc.request.AddProductReq;
import com.lbtc.request.ProductListReq;
import com.lbtc.request.UpdateProductReq;
import com.lbtc.service.CategoryService;
import com.lbtc.service.ProductService;
import com.lbtc.vo.CategoryVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class ProductServiceImpl implements ProductService {

    @Resource
    private ProductMapper productMapper;

    @Override
    public void add(AddProductReq addProductReq) throws LbtcMallException {
        Product product = new Product();
        BeanUtils.copyProperties(addProductReq,product);
        Product name = productMapper.selectByName(addProductReq.getName());
        if (name!=null) {
            throw new LbtcMallException(LbtcMallExceptionEnum.NAME_EXISTED);
        }
        int i = productMapper.insert(product);
        if (i==0) {
            throw new LbtcMallException(LbtcMallExceptionEnum.CREATE_FAILED);
        }
    }

    @Override
    public void update(UpdateProductReq updateProductReq ) throws LbtcMallException {
        Product product = new Product();
        BeanUtils.copyProperties(updateProductReq, product);
        Product productOld = productMapper.selectByName(updateProductReq.getName());
        //同名且不同id，不能继续修改
        if (productOld != null && !productOld.getId().equals(updateProductReq.getId())) {
            throw new LbtcMallException(LbtcMallExceptionEnum.NAME_EXISTED);
        }
        int count = productMapper.updateByPrimaryKeySelective(product);
        if (count == 0) {
            throw new LbtcMallException(LbtcMallExceptionEnum.UPDATE_FAILED);
        }
    }
    @Override
    public void delete(Integer id) throws LbtcMallException {
        Product productOld = productMapper.selectByPrimaryKey(id);
        //查不到该记录，无法删除
        if (productOld == null) {
            throw new LbtcMallException(LbtcMallExceptionEnum.DELETE_FAILED);
        }
        int count = productMapper.deleteByPrimaryKey(id);
        if (count == 0) {
            throw new LbtcMallException(LbtcMallExceptionEnum.DELETE_FAILED);
        }
    }

    @Override
    public void batchUpdateSellStatus(Integer[] ids, Integer sellStatus) {
        productMapper.batchUpdateSellStatus(ids, sellStatus);
    }

    @Override
    public PageInfo listForAdmin(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<Product> products = productMapper.selectListForAdmin();
        PageInfo pageInfo = new PageInfo(products);
        return pageInfo;
    }

    @Override
    public Product detail(Integer id){
        Product product = productMapper.selectByPrimaryKey(id);
        return product;
    }

    @Autowired
    private CategoryService categoryService;
    @Override
    public PageInfo list(ProductListReq productListReq){
        //先构建一个专门助力于查询的Query对象
        ProductListQuery productListQuery = new ProductListQuery();
        //搜索条件处理
        //如果前端传了keyword这个参数；就把这个条件赋值到productListQuery查询对象上去；
        if (!StringUtils.isEmpty(productListReq.getKeyword())) {
            //根据keyword拼凑"%keyword%",以好在数据库中进行模糊查询;
            String keyword = new StringBuilder().append("%").append(productListReq.getKeyword()).append("%").toString();
            //然后，把这个在查询数据库时，可以直接使用的"%keyword%"查询条件，赋值到productListQuery查询对象上去；
            productListQuery.setKeyword(keyword);
        }
        //如果前端传了categoryId这个参数；（也就是前端选择某个商品目录）：就把这个条件赋值到productListQuery查询对象上去；
        if (productListReq.getCategoryId() != null) {
            //目录处理：如果查询某个目录下的商品，不仅要查询隶属于该目录下的商品，也要查询隶属于该目录的子目录下的商品；
//            List<CategoryVO> categoryVOList = categoryService.listCategoryForCustomer(productListReq.getCategoryId());
            List<CategoryVO> categoryVOList = categoryService.listForCustomer(productListReq.getCategoryId());
            //创建一个List用来存放所有的CategoryId
            ArrayList<Integer> categoryIds = new ArrayList<>();
            categoryIds.add(productListReq.getCategoryId());
            getCategoryIds(categoryVOList, categoryIds);
            //把在查询数据库时，当前目录和当前目录所有子目录的categoryIds的查询条件，赋值到productListQuery查询对象上去；
            productListQuery.setCategoryIds(categoryIds);
        }

        //排序条件的处理
        String orderBy = productListReq.getOrderBy();
        if (Constant.ProductListOrderBy.PRICE_ASC_DESC.contains(orderBy)) {
            PageHelper.startPage(productListReq.getPageNum(), productListReq.getPageSize(), orderBy);
        } else {
            PageHelper.startPage(productListReq.getPageNum(), productListReq.getPageSize());
        }


        //调用Dao层编写的(可能有条件的)查询语句
        List<Product> productList = productMapper.selectList(productListQuery);
        PageInfo pageInfo = new PageInfo(productList);
        return pageInfo;
    }
    //递归获取子目录信息
    private void getCategoryIds(List<CategoryVO> categoryVOList, ArrayList<Integer> categoryIds) {
        for (int i = 0; i < categoryVOList.size(); i++) {
            CategoryVO categoryVO = categoryVOList.get(i);
            if (categoryVO != null) {
                categoryIds.add(categoryVO.getId());
                getCategoryIds(categoryVO.getChildCategory(), categoryIds);
            }
        }
    }
}
